<?php

namespace app\api1\controller;

use hg\apidoc\annotation as Apidoc;
use hg\apidoc\annotation\Param;
use hg\apidoc\annotation\Query;
use hg\apidoc\annotation\Returned;
use hg\apidoc\annotation\Header;
use app\BaseController;
use think\facade\View;
use think\facade\Db;
use think\response\Json;

class RobotConversation extends Auth
{
    /**
     * list
     * @Apidoc\Title("列表")
     * @Query(key="start_time", rule="string", default="", desc="开始时间")
     * @Query(key="end_time", rule="string", default="", desc="结束时间")
     */
    public function list()
    {
        $where = [];
        $robot_id = input('robot_id', 0, 'intval');
        if($robot_id){
            $where[] = ['robot_id', '=', $robot_id];
        }
        if(input('chat_id')){
            $where[] = ['id', '=', input('chat_id')];
        }else{
            $start_time = input('start_time');
            $end_time = input('end_time');
            if($start_time && $end_time){
                $start_time = strtotime($start_time);
                $end_time = strtotime($end_time) + 86400 -1;
                $where[] = ['create_time', 'between', [$start_time, $end_time]];
            }
        }
        $res = \app\common\model\RobotConversation::where($where)
            ->order('id' ,'desc')->paginate(input('page_size',10, 'intval'))
            ->each(function($item){
               $item['count_msg'] = \app\common\model\RobotConversationMessage::where('robot_conversation_id', $item['id'])->count();
               $event = \app\common\model\RobotConversationMessage::where('robot_conversation_id', $item['id'])
                     ->where('is_event_submission', 1)->find();
               if($event) {
                   $item['event'] = $event['is_event_submission'];
                   $item['user_name'] = $event['user_submission']['姓名'];
               }else{
                   $item['user_name'] = '用户' . $item['id'];
               }
                return $item;
            })
        ;
        return success('ok', $res);

    }

   /**
     * getById
     * @Apidoc\Method("post")
     * @Apidoc\Title ("获取对话详情")
     * @Query(key="id", rule="int", default="", desc="id")
     */
    public function getById()
    {
        $id = input('id', 0, 'intval');
        $res = \app\common\model\RobotConversation::find($id);
        $messages = \app\common\model\RobotConversationMessage::where('robot_conversation_id', $id)
            ->order('id', 'asc')->select()
            ->each(function($item){
                $item['answer_time_str'] = date('Y-m-d H:i:s', $item['answer_time']);
                $item['isActive'] = false;
                return $item;
            });
        return success('ok', [
            'conversation' => $res,
            'messages' => $messages
        ]);
    }
}
